import { createApp, type App, type Component } from 'vue';

// 加载组件 - 可以替换为你自己的加载组件
const LoadingComponent: Component = {
  template: `
    <div class="loading-overlay">
      <div class="loading-spinner">
        <div class="spinner"></div>
        <div class="loading-text">加载中...</div>
      </div>
    </div>
  `
};

// 创建加载实例
let loadingInstance: App | null = null;
let loadingCount = 0; // 加载计数器

export function showLoading(target: string | HTMLElement = 'body') {
  if (loadingCount === 0) {
    const container = document.createElement('div');
    container.id = 'loading-container';
    
    const targetElement = typeof target === 'string' 
      ? document.querySelector(target) 
      : target;
    
    if (targetElement) {
      targetElement.appendChild(container);
      loadingInstance = createApp(LoadingComponent);
      loadingInstance.mount(container);
    }
  }
  loadingCount++;
}

export function hideLoading() {
  if (loadingCount <= 0) return;
  
  loadingCount--;
  
  if (loadingCount === 0 && loadingInstance) {
    loadingInstance.unmount();
    const container = document.getElementById('loading-container');
    if (container && container.parentNode) {
      container.parentNode.removeChild(container);
    }
    loadingInstance = null;
  }
}

// 样式可以直接放在组件中，或者全局样式表中
const loadingStyles = `
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }
  
  .loading-spinner {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  .loading-text {
    margin-top: 10px;
    color: #333;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
`;

// 动态添加样式
const styleElement = document.createElement('style');
styleElement.innerHTML = loadingStyles;
document.head.appendChild(styleElement);